#include <TFT_eSPI.h>
#include <MPU6050_tockn.h>
#include <Wire.h>
#include <SPI.h>

#ifndef TFT_DISPOFF
#define TFT_DISPOFF 0x28
#endif

#ifndef TFT_SLPIN
#define TFT_SLPIN   0x10
#endif

#define TIME 3000
#define POWER_ADC 27//ADC引脚

#define TFT_BL  4  // Display backlight control pin
int freq1 = 2000;    // 频率
int channel1 = 0;    // 通道0，共16个通道，0~15
int resolution1 = 10;   // 分辨率，取值0~20，duty最大取值为2^resolution-1
int bright = 20;
float arg1,arg2;

TFT_eSPI tft = TFT_eSPI(135, 240); // Invoke custom library
MPU6050 mpu6050(Wire);

void setup()
{
  Serial.begin(115200);
  Serial.println("Start");

  adcAttachPin(POWER_ADC);//将引脚连接到ADC
  adcStart(POWER_ADC);//在连接的引脚总线上开始ADC转换
  analogReadResolution(16);//设置aliogRead返回值的分辨率

  ledcSetup(channel1, freq1, resolution1); // 设置通道0
  ledcAttachPin(TFT_BL, channel1);  // 将通道0与引脚25连接
  ledcWrite(channel1, bright);  // 输出PWM

  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);

  tft.init();
  tft.setRotation(1);
  tft.fillScreen(TFT_BLACK);
  tft.setTextSize(2);
  tft.setTextColor(TFT_YELLOW, TFT_BLACK);

  delay(1000);

  mpu6050.update();
  float arg1 = mpu6050.getAngleZ();
}

void loop()
{

  tft.fillRoundRect(20,15,(200*bright)/1023,16,4,TFT_WHITE);
  
  tft.setTextColor(TFT_BLUE, TFT_BLACK);
  tft.drawString("AngleZ:", 0, 50, 1);
  tft.drawFloat(arg2,2, 100, 50, 1);
  tft.drawString("*", 220, 50, 1);

  tft.setTextColor(TFT_YELLOW, TFT_BLACK);
  float power_adc = 2*((analogRead(POWER_ADC)*3.3)/65535)+0.4;
  tft.drawString("V:", 0, 75, 1);
  tft.drawFloat(power_adc,2, 100, 75, 1);
  tft.drawString("V", 220, 75, 1);

  delay(50);

  mpu6050.update();
  float arg2 = mpu6050.getAngleZ();
  bright = bright + (arg2-arg1)*5;
  bright = bright>1023?1023:bright;
  bright = bright<20?20:bright;
  arg1 = arg2;
  ledcWrite(channel1, bright);  // 输出PWM

  tft.fillScreen(TFT_BLACK);
}